﻿using MassTransit;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using Tiens.NotificationHub.IntegrationEvents;
using Tiens.NotificationHub.Services;

namespace Tiens.NotificationHub.Core.Consumers
{
    public class NotifyingAllUsersWithAppIdConsumer: IConsumer<NotifyingAllUsersWithAppIdEvent>
    {
        private readonly IHubContext<NotificationsHub> _hubContext;
        private readonly ILogger<NotifyingAllUsersWithAppIdConsumer> logger;
        private readonly IAppConnectionManager _appConnectionManager;

        public NotifyingAllUsersWithAppIdConsumer(IHubContext<NotificationsHub> hubContext,
            ILogger<NotifyingAllUsersWithAppIdConsumer> logger,
            IAppConnectionManager appConnectionManager)
        {
            _hubContext = hubContext;
            this.logger = logger;
            _appConnectionManager = appConnectionManager;
        }

        public async Task Consume(ConsumeContext<NotifyingAllUsersWithAppIdEvent> context)
        {
            logger.LogInformation("NotifyingAllUsersWithAppIdConsumer[appId:{appId},message:{message}]", context.Message.AppId, context.Message.Message);
            var tasks = (await _appConnectionManager.GroupsByAppIdAsync(context.Message.AppId))
                .Select(x =>
                    _hubContext.Clients.Groups(x).SendAsync(nameof(NotifyingAllUsersWithAppIdEvent), context.Message.Message));

            if (tasks.Any())
                await Task.WhenAll(tasks);
        }
    }
}
